using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Orbitone.MeetingRooms.Services;
using Orbitone.MeetingRooms.Services.Model;

namespace Orbitone.MeetingRooms.RoomFinder.UserControls
{
    public partial class CreateCalendarItem : UserControl
    {
        public string LoginId { get; set; }
        public string LoginUsername { get; set; }

        public DateTime SelectedDate { get; set; }

        public List<MailboxModel> Rooms { get; set; }
        public IExchangeService ExchangeService { get; set; }

        public CalendarItemModel CalendarItemModel { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                var span = new TimeSpan(0, 0, 30, 0);
                long ticks = (SelectedDate.Ticks + span.Ticks - 1)/span.Ticks;
                var start = new DateTime(ticks*span.Ticks);
                DateTime end = start.AddMinutes(60);

                CalendarItem.CalendarItemModel = CalendarItemModel ?? new CalendarItemModel
                                                                          {
                                                                              Rooms =
                                                                                  Rooms.Select(
                                                                                      r =>
                                                                                      new ListItem
                                                                                          {
                                                                                              Text = r.DisplayName,
                                                                                              Value = r.EmailAddress
                                                                                          }).
                                                                                  ToList(),
                                                                              Date = SelectedDate,
                                                                              StartTime =
                                                                                  DateTime.ParseExact(
                                                                                      SelectedDate.ToString("yyyyMMdd") +
                                                                                      "T" + start.ToString("HH:mm:ss"),
                                                                                      "yyyyMMddTHH:mm:ss", null),
                                                                              EndTime =
                                                                                  DateTime.ParseExact(
                                                                                      SelectedDate.ToString("yyyyMMdd") +
                                                                                      "T" + end.ToString("HH:mm:ss"),
                                                                                      "yyyyMMddTHH:mm:ss", null),
                                                                              SubjectEnabled = true,
                                                                              ValidationGroup = "createItem",
                                                                              Title = "Reservation",
                                                                              TitleButton = "Create"
                                                                          };
            }
        }


        protected void CreateEvent(object sender, EventArgs e)
        {
            CalendarItemModel item = CalendarItem.CalendarItemModel;
            var model = new CalendarEventModel
                            {
                                StartDate = item.StartTime,
                                EndDate = item.EndTime,
                                Mailbox = item.RoomEmail,
                                Subject = item.Subject,
                                UserName = LoginUsername,
                                UserId = LoginId,
                            };

            if (model.StartDate.CompareTo(DateTime.Now) < 0)
            {
                lblerror.Text = "Start date is in the past.";
                ErrorPanel.Visible = true;
                return;
            }
            if (model.StartDate.CompareTo(model.EndDate) >= 0)
            {
                lblerror.Text = "End date before or equal to start date, this is not a valid combination.";
                ErrorPanel.Visible = true;
                return;
            }

            List<AvailabilityModel> availability = ExchangeService.GetAvailability(Rooms, model.StartDate, model.EndDate,
                                                                                   30);
            IEnumerable<CalendarEventModel> evts = null;
            AvailabilityModel events =
                availability.Where(m => m.Mailbox.EmailAddress.Equals(model.Mailbox)).FirstOrDefault();
            if (events != null)
            {
                evts = events.CalendarEvents.Where(c => (model.EndDate <= c.StartDate) || (model.StartDate >= c.EndDate));
            }

            if (evts != null && evts.Count() < events.CalendarEvents.Count)
            {
                lblerror.Text = "Can not create appointment, because of overlapping time";
                ErrorPanel.Visible = true;
            }
            else
            {
                ExchangeService.SaveAppointment(model);

                string date = model.StartDate.ToString("ddMMyyyy");
                Response.Redirect("Calendar.aspx?Date=" + date);
            }
        }
    }
}